<template>
	<view class="container">
		<view v-for="(item, index) in list" :key="index" class="item" @click="itemClick(item)">
			<view class="name">
				{{item.name}}
			</view>
			<view class="desc">
				{{item.deviceId}}
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				timeoutID: 0,
				
				list: [],
			}
		},
		onLoad() {
			this.startDiscovery();
		},
		onUnload() {
			this.stopDiscovery();
		},
		methods: {			
			//开始搜索设备
			startDiscovery() {
				let self = this;
				this.timeoutID = setTimeout(function() {
					uni.startBluetoothDevicesDiscovery({
						success: res => {
							self.setBluetoothDeviceFound();
						},
						fail: res => {
							console.log("查找设备失败!");
							uni.showToast({
								icon: "none",
								title: "查找设备失败！请检查是否打开蓝牙权限",
								duration: 1000
							})
						}
					});
				}, 500);
			},
			//停止搜索设备
			stopDiscovery() {
				let that = this;
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log('停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
					}
				});
			},
			
			setBluetoothDeviceFound() {
				console.log("监听寻找新设备");
				uni.onBluetoothDeviceFound(devices => {
					console.log('开始监听寻找到新设备的事件');
					this.getBluetoothDevices();
				});
			},
			
			getBluetoothDevices() {
				console.log("获取蓝牙设备");
				let that = this;
				uni.getBluetoothDevices({
					success: res => {
						console.log('获取蓝牙设备成功:' + res.errMsg);
						console.log(res)
						that.list = res.devices;
					}
				});
			},
			
			itemClick(item) {
				this.stopDiscovery();
				console.log(item);
				const eventChannel = this.getOpenerEventChannel();
				eventChannel.emit('bluetoothEvent', item);
				uni.navigateBack({})
			},
		}
	}
</script>

<style lang="scss">
	page{
		background-color: $app-page-bg-color;
	}
	.container{
		display: flex;
		flex-direction: column;
		padding-left: 30rpx;
		padding-right: 30rpx;
		padding-top: 30rpx;
	}
	.item{
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		
		.name{
			font-size: 26rpx;
			font-family: PingFang SC;
			font-weight: bold;
			color: #333333;
		}
		
		.desc{
			font-size: 24rpx;
			font-family: PingFang SC;
			font-weight: 400;
			color: #333333;
			margin-top: 10rpx;
		}
	}
</style>
